package com.cn.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.*;
import java.util.Properties;

public class FileConfigPropertyUtil {

    private Properties properties;

    public FileConfigPropertyUtil(String dir) throws IOException {
        if (StringUtils.isEmpty(dir)) {
            throw new RuntimeException("文件不存在");
        }
        this.properties = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(dir));
        if (in != null) {
            this.properties.load(in);
        }
    }

    public FileConfigPropertyUtil() throws IOException {
        this.properties = new Properties();
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resuorce = resourceLoader.getResource("classpath:/system.properties");
        properties.load(new FileReader(resuorce.getFile()));
    }

    public String get(String key) {
        if (properties != null) {
            return this.properties.getProperty(key);
        }
        return null;
    }

    public static Properties get(String fileName, String name) {
        if (StringUtils.isEmpty(fileName)) {
            throw new RuntimeException("配置文件不存在");
        }
        try {
            Properties properties = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream(fileName));
            if (in != null) {
                properties.load(in);
            }
            return properties;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void put(String config, String key, String value, String comment) throws
            FileNotFoundException, IOException {
        if (StringUtils.isEmpty(config)) {
            throw new RuntimeException("配置信息异常");
        }
        FileOutputStream fos = new FileOutputStream(new File(config), true);
        Properties prop = new Properties();
        prop.put(key, value);
        prop.store(fos, comment);
    }

    public static void main(String[] args) {
        String config = "F:/config.properties";
        Properties p = get(config, null);
        System.out.println(p);
        if (p != null) {
            System.out.println(p.get("config_dir"));
        }
        try {
            put(config, "tel", "15002694620", "hi this demo!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
